const app = getApp()
const global = app.globalData;
var util = require('../../utils/util.js');
const bleUtil = require('../../utils/bu01BleUtil.js')
const bu01Reader = require('../../utils/bu01Reader.js')
const errorCode = require('../../utils/errorCode.js')
var Promise = require('../../utils/es6-promise.js')
var bleParams = {
  connectedDeviceId: '',
  serviceId: '',
  characteristicId: ''
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bannerImg: [
      { link: '', imgs: '../../images/head.jpg' },
      { link: '', imgs: '../../images/head2.jpg' },
    ],
    info: null,
    time: 0,
    orderid: '',
    orderStatus: null,
    firstTime: 0,
    deviceCode: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.error = new errorCode.ErrorCode()
    this.getIndex()
    if (app.globalData.deviceCode){
      this.getCharge()
      this.setData({
        deviceCode: app.globalData.deviceCode
      })
    }
  },
  getCharge() {
    let _this = this
    let token = wx.getStorageSync("token")
    let deviceCode = app.globalData.deviceCode
    wx.request({
      url: global.APIURL + 'api/v1/charge?deviceCode=' + deviceCode,
      header: {
        'Authorization': token
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == '200') {
          _this.setData({
            info: res.data.data,
            deviceCode: app.globalData.deviceCode
          })
        }
      }
    })
  },
  getCaption(obj) {
    var index = obj.lastIndexOf("\?");
    obj = obj.substring(index + 1, obj.length);
    return obj;
  },
  checkId() {
    let _this = this
    wx.scanCode({
      success: (res) => {
        console.log(res.path)
        var startIndex = res.result.indexOf("device_id=");
        var code = res.result.substring(startIndex + 10);
        app.globalData.deviceCode = code
        this.setData({
          deviceCode: code
        })
        _this.getCharge()
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },
  getIndex() {
    let _this = this
    let token = wx.getStorageSync("token")
    wx.request({
      url: global.APIURL + 'api/v1/index',
      data: '',
      header: {
        'Authorization': token
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == '200') {
          _this.setData({
            bannerImg: res.data.data
          })
          global.bannerImg = res.data.data;
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },
  initBlt(callback) {
    console.log('初始化调用.....')
    var that = this
    //连接蓝牙
    if (!app.globalData.connection) {
      bleParams.deviceCode = app.globalData.deviceCode;
      that.ble = new bleUtil.BU01BleUtil(bleParams)
      that.ble.iniBle()
        .then((res) => {
          that.ble.findDevices(deviceId => {
            that.ble.connect(deviceId)
              .then(() => {
                if (app.globalData.connectedDeviceId) {
                  wx.hideLoading()
                  this.reader = new bu01Reader.BU01Reader()
                  this.reader.monitor()
                  callback();
                }
              })
          })
        })
        .catch(res => {
          wx.hideLoading()
          console.log('初始化蓝牙失败', res)
          if (getApp().globalData.platform == 'ios') {
            that.error.getErrorMsg('初始化蓝牙失败', res)
          } else {
            that.error.getErrorMsg('初始化蓝牙失败', 10001)
          }
          app.globalData.discovering = false
        })
    } else if (app.globalData.available) {
      this.reader = new bu01Reader.BU01Reader()
      this.reader.monitor()
      callback();
    }
  },
  buy(e) {
    let _this = this
    let packagePrice = e.currentTarget.dataset.goods.price
    let time = e.currentTarget.dataset.goods.time
    this.setData({
      time: time
    })
    this.initBlt(() => {
      _this.checkNum(packagePrice)
    })
  },
  checkNum(price){
    let _this = this
    wx.showLoading({
      title: '下单中...',
      mask: true
    })
    let token = wx.getStorageSync("token")
    let deviceCode = app.globalData.deviceCode
    var parameter = {
      deviceCode: deviceCode,
      packagePrice: price
    };
    wx.request({
      url: global.APIURL + 'api/v1/order',
      data: parameter,
      header: {
        'Authorization': token,
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        console.log(res)
        if (res.data.code == '200') {
          let result = res.data.data.result
          _this.setData({
            orderid: res.data.data.orderid
          })
          wx.requestPayment({
            timeStamp: result.timeStamp,
            nonceStr: result.nonceStr,
            package: result.packageValue,
            signType: result.signType,
            paySign: result.paySign,
            success(res2) {
              _this.getStatus()
            },
            fail(error) {
              util.toast('未付款，已取消订单')
            }
          })
        }
      }
    })
  },
  getStatus() {
    let _this = this
    wx.showLoading({
      title: '正在操作中',
      mask:true
    })
    var timeTask = setInterval(function () {
      _this.data.time++;
      _this.queryresult()
      if (_this.data.orderStatus == '0') {
        console.log('付款成功')
        clearInterval(timeTask);
      } else if (_this.data.time == '60') {
        util.toast('已超时')
        clearInterval(timeTask);
      }
    }, 1000)
  },
  queryresult() {
    let _this = this
    let token = wx.getStorageSync("token")
    let deviceCode = app.globalData.deviceCode
    wx.request({
      url: global.APIURL + '/api/v1/order/status?orderId=' + _this.data.orderid,
      header: {
        'Authorization': token,
      },
      success: function (res) {
        if (res.data.code == '200') {
          wx.hideLoading();
          console.log(res.data.data)
          _this.setData({
            orderStatus: res.data.data.orderStatus
          })
          if (res.data.data.orderStatus == '0') {
            
            // 发起指令之后 修改订单状态
            if (_this.data.firstTime == 0){
              _this.setData({
                firstTime: 1
              })
            // lanyaModule.sendRechargeCmd('1234561234561')
              // lanyaModule.sendRechargeCmd(res.data.data.password.currentPassword + res.data.data.password.nextPassword + '1')
              let time = 1;
              if (_this.data.time!="4"){
                time = 2;
              }
              _this.reader.sendRechargeCmd(res.data.data.password.currentPassword + res.data.data.password.nextPassword + time).then(res=>{
                console.log("收到数据" + res);
                if (res != 0) {
                  util.toast("购买失败，请联系工作人员！");
                }
                var parameter = {
                  orderId: _this.data.orderid,
                  status: res == 0 ? '1' : '4',
                  msg: res
                }
                // 修改状态
                wx.request({
                  url: global.APIURL + 'api/v1/order/status',
                  data: parameter,
                  header: {
                    'Authorization': token,
                    'Content-Type': 'application/x-www-form-urlencoded'
                  },
                  method: 'POST',
                  success: function (res1) {
                    if (res1.data.code == '200') {
                      wx.hideLoading();
                      util.toast('操作完成');
                      _this.setData({
                        firstTime: 0
                      })
                    }
                  }
                })
              })  
            }
          } else if (res.data.data.orderStatus == '1') {
            wx.hideLoading();
            _this.setData({
              firstTime: 0
            })
          }
        } else {
          util.toast(res.message);
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if (app.globalData.available && app.globalData.discovering) {
      this.stopSearchBle()
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (app.globalData.available) {
      if (app.globalData.discovering) {
        this.stopSearchBle()
      }
    }
    if (app.globalData.connection) {
      //关闭蓝牙适配器
      this.ble.closeBle()
        .catch((res) => {
          this.error.getErrorMsg('关闭蓝牙出错', res)
        })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // showPwd:function(){
  //   wx.navigateTo({
  //     url: '../code/code',
  //   })
  // }
})